<?php

//根据参数，生成sql查询语句"select $colSel from $table where $colCon = $var",返回结果集
function query($con, $colSel, $table, $colCon, $var)
{
	/*$con = mysql_connect("localhost", "root", "fdj1924");
	
	if (!mysql_select_db("lab", $con))
	{
	die ("Can't use lab : " . mysql_error());
	}*/
	
	$sql = "select ".$colSel." from ".$table." where ".$colCon."='".$var."'";
	//echo $sql."<br />";
	
	if (!$result = mysql_query($sql, $con))
	{
		//echo "query successfully!";
		//mysql_close($con);
		die("Error querying database: " . mysql_error());
		//return false;
	}
	else
	{
		$num = mysql_num_rows($result);
		//echo "num of rows:".$num."<br />";
		//echo $sql."<br />";
		return $result;
	}

	//mysql_close($con);
}

//有副作用，不可轻易使用
function extractCol($result, $colName)
{
	$row = mysql_fetch_array($result);
	
	if(!$row)
	{
		echo "No row!<br />";
	}
	else if($row[$colName] == '')
	{
		echo "No column data";
	}
	else
	{
		return $row[$colName];
	}
}


function connect($host, $user, $password, $db)
{
	$con = @mysql_connect($host, $user, $password);
	
	mysql_query("set names utf8");
	
	if (!$con)
	{
		die('Could not connect: ' . mysql_error());
	}
	else
	{
		//echo $db."<br />";
		if(!mysql_select_db($db, $con))
		{
			die('Could not connect: ' . mysql_error());
		}
		return $con;
	}
}

function insertIntoDB($con, $table, $data)
{
	$sql = "insert into ".$table." values(";
	
	for($i = 0; $i < count($data)-1; $i++)
	{
		$sql = $sql."'".$data[$i]."',";
	}
	
	$sql = $sql."'".$data[count($data)-1]."');";
	//echo $sql."<br />";
	
	//mysql_query($sql, $con) or die("insert error!");
	if(mysql_query($sql, $con))
	{
		return true;
	}
	else
	{
		die("insert error:".mysql_error());
	}
}

function replaceEnter($subject)
{
	str_replace(" ", "<br/>", $subject);
	str_replace("\r\n", "<br/>", $subject);
	str_replace("\n", "<br/>", $subject);
	str_replace("\r", "<br/>", $subject);	
}

function update($con, $talbe, $colUpd, $var)
{
	$sql = "update ".$table." set ".$colUpd."='".$var."'";
	//echo $sql;
	
	if(!mysql_query($sql, $con))
	{
		die("Error querying database: " . mysql_error());	
		//return false;
	}
	else
	{
		return true;
	}
}


//$con = connect("10.108.104.190", "hh", "", "lab");
//$result = query($con, "*", "projecteam", "ID", '1');
//$data = array("2", "HangHuan", "Hello");
//insertIntoDB($con, "projecteam", $data);
//update($con, "personalinfo", "email", $);
//$name = extractCol($result, "name");

//echo $name."<br />";

?>